package com.vshop.framework.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public final class ThreadContextMap {

    private static final ThreadLocal<Map<String, String>> localMap = new TransmittableThreadLocal<>();

    public static void put(final String key, final String value) {
        Map<String, String> map = localMap.get();
        map = map == null ? new HashMap<>() : new HashMap<>(map);
        map.put(key, value);
        localMap.set(Collections.unmodifiableMap(map));
    }

    public static String get(final String key) {
        final Map<String, String> map = localMap.get();
        return map == null ? null : map.get(key);
    }

    public static void remove(final String key) {
        final Map<String, String> map = localMap.get();
        if (map != null) {
            final Map<String, String> copy = new HashMap<String, String>(map);
            copy.remove(key);
            localMap.set(Collections.unmodifiableMap(copy));
        }
    }

    public static void clear() {
        localMap.remove();
    }

    public static boolean containsKey(final String key) {
        final Map<String, String> map = localMap.get();
        return map != null && map.containsKey(key);
    }


    public static boolean isEmpty() {
        final Map<String, String> map = localMap.get();
        return map == null || map.isEmpty();
    }

    public static Map<String, String> getCopy() {
        final Map<String, String> map = localMap.get();
        return map == null ? new HashMap<String, String>() : new HashMap<String, String>(map);
    }


    public static Map<String, String> getImmutableMapOrNull() {
        return localMap.get();
    }
}
